import urequests
from machine import Pin, I2S
import time
from config import SEVER_URL,BCLK,LRC,DIN

# 定义板载灯连接的 GPIO 引脚
led_pin = Pin(2, Pin.OUT)

def get_synthesized_audio():
    server_url = SEVER_URL
    # 获取程序开始时间
    program_start_time = time.ticks_ms()
    # 获取开始时间（放到播放音乐前）
    start_play_preparation_time = time.ticks_ms()
    # 初始化引脚定义
    bclk = Pin(BCLK) # 串行时钟输出--- BCLK
    lrc  = Pin(LRC)  # 字时钟--- LRC
    din  = Pin(DIN)  # 串行数据输出--- DIN
    audio_out = I2S(1, sck=bclk, ws=lrc, sd=din, mode=I2S.TX, bits=16, format=I2S.MONO, rate=16000, ibuf=20000)
    response = urequests.get(server_url+'/upload')
    response.close()
    del response
    response = urequests.get(server_url+'/asr_result', stream=True)
    led_pin.value(0)
    # 获取开始播放音频的时间
    start_play_time = time.ticks_ms()
    print("开始播放音频...请求状态码：", response.status_code)
    try:
       while True:
           content_byte = response.raw.read(512)
           if content_byte:
               print("接收到数据长度：", len(content_byte))
               audio_out.write(content_byte)
               print("Wrote audio data.")
           else:
               break
    except Exception as ret:
       print("程序产生异常...", ret)
       audio_out.deinit()
    finally:
       # 获取结束时间
       end_play_preparation_time = time.ticks_ms()
       play_preparation_duration = (end_play_preparation_time - start_play_preparation_time) / 1000
       
       # 计算从程序开始到开始播放音频的时间
       program_to_play_duration = (start_play_time - program_start_time) / 1000
       print(f"从程序开始到开始播放音频耗时: {program_to_play_duration} 秒")
       print(f"总耗时: {play_preparation_duration} 秒")
